// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'
import Base from './common/base'
import 'element-ui/lib/theme-chalk/index.css'
import ElementUI from 'element-ui'

Vue.config.productionTip = false
Vue.use(ElementUI)

axios.interceptors.request.use(
  config => {
    if (localStorage.getItem('token')) {
      config.headers['Authorization'] = localStorage.getItem('token')
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      console.log('to login...')
      location.href = '/login?redirect=' + encodeURIComponent(location.href)
    } else if (error.response.status === 409) {
      return Promise.reject(error)
    } else if (error.response.status > 400 && error.response.status < 500) {
      if (error.response.data.msg) {
        ElementUI.Message({
          type: 'error',
          showClose: true,
          message: error.response.data.msg
        })
      }
    }
  }
)

Vue.prototype.$axios = axios
Vue.prototype.$base = new Base()

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: {App},
  template: '<App/>'
})
